import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'
import Index from '../views/Index'

import axios from "../utils/request";
import store from "../store"


// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/index',
    children: [
      {
        path: '/index',
        name: 'Index',
        meta: {
          title: "首页"
        },
        component: Index
      },
      {
        path: '/userCenter',
        name: 'UserCenter',
        meta: {
          title: "个人中心"
        },
        component: () => import('@/views/UserCenter')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next) => {

  // 只有在第一次访问时绑定所有路由
  let hasRoute = store.state.menus.hasRoute

  //token没有后就跳转到登录页
  let token = localStorage.getItem("token")
  if(to.path === '/login'){
    next()
  }else if (!token){
    next({path: '/login'})
  // 没有绑定过，我们就进行绑定
  }else if(token && !hasRoute){
    // 获取信息
    axios.get("/sys/menu/nav", {
      headers: {
        Authorization: localStorage.getItem("token")
      }
    }).then(res => {
      // 拿到menuList信息
      store.commit("setMenuList", res.data.nav)
      // 拿到用户的权限
      store.commit("setPermList",res.data.authoritys)

      // 动态绑定路由
      let newRoutes = router.options.routes

      res.data.nav.forEach(menu => {
        // 判断是否有子菜单
        if(menu.children) {
          // 有子菜单，我们就进行绑定
          menu.children.forEach(item => {
            // 转换路由
            let route = menuToRoute(item)
            // 把路由添加到路由管理中
            if(route){
              // 都要添加到Home下面
              newRoutes[0].children.push(route)
            }
          })
        }
      })
      router.addRoutes(newRoutes)
      // 第一次绑定完成后就改变值，不再进行绑定了
      hasRoute = true
      store.commit("changeHasRoute", hasRoute)
    })
  }

  next()
})

// 转换路由
const menuToRoute = (menu) => {
  if(!menu.component){
    return null
  }

  let route = {
    name: menu.name,
    path: menu.path,
    meta: {
      icon: menu.icon,
      title: menu.title
    }
  }

  route.component = () => import('@/views/' + menu.component)

  return route
}

export default router
